/*
 *     This file is part of Mobile GPS Logger.
 *
 *     Mobile GPS Logger is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Mobile GPS Logger is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License v3 for more details.
 *
 *     You should have received a copy of the GNU General Public License v3
 *     along with Mobile GPS Logger. If not, see <http://www.gnu.org/licenses/>.
 */

package cx.ath.skyflyer.gpslog.nmea;

/**
 *
 * @author Ahti Legonkov
 */
public class Time {

    public Time(String s) throws NumberFormatException {
        double d = Double.parseDouble(s);
        double milliseconds = d - Math.floor(d);
        m_Millisecond = (int)(1000 * milliseconds);
        int hhmmss = (int)(d-milliseconds);
        m_Second = hhmmss % 100;
        int hhmm = hhmmss/100;
        m_Minute = hhmm % 100;
        m_Hour = hhmm / 100;

        m_Time = (double)(3600*m_Hour + 60*m_Minute + m_Second) + milliseconds;
    }

    public int getHour() {
        return m_Hour;
    }

    public int getMinute() {
        return m_Minute;
    }

    public int getSecond() {
        return m_Second;
    }

    public int getMillisecond() {
        return m_Millisecond;
    }

    private static void appendWithLeadZero(StringBuffer sb, int n) {
        if (n < 10)
            sb.append('0');
        sb.append(n);
    }

    public String toString() {
        StringBuffer sb = new StringBuffer(15);
        appendWithLeadZero(sb, m_Hour);
        sb.append(':');
        appendWithLeadZero(sb, m_Minute);
        sb.append(':');
        appendWithLeadZero(sb, m_Second);
        if (m_Millisecond > 0) {
            sb.append('.');
            if (m_Millisecond < 100)
                sb.append('0');
            if (m_Millisecond < 10)
                sb.append('0');
            sb.append(m_Millisecond);
        }
        return sb.toString();
    }

    public int hashCode() {
        int hash = 7;
        hash = 53 * hash + (int) (Double.doubleToLongBits(this.m_Time) ^ (Double.doubleToLongBits(this.m_Time) >>> 32));
        return hash;
    }

    public boolean equals(Object o) {
        if (!(o instanceof Time))
            return false;

        Time t = (Time)o;
        return t != null
            && t.m_Hour == m_Hour
            && t.m_Minute == m_Minute
            && t.m_Second == m_Second
            && t.m_Millisecond == m_Millisecond
            ;
    }

    public double sub(Time other) {
        return m_Time - other.m_Time;
    }

    private int m_Hour;
    private int m_Minute;
    private int m_Second;
    private int m_Millisecond;
    private double m_Time;

}
